package com.tanhua.dubbo.api;

import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.UserComment;
import com.tanhua.model.mongo.Video;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author ck
 * @date 2021/11/18 20:02
 */

@DubboService
public class UserCommentApiImpl implements UserCommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public List<UserComment> find(Long vUserId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("vUserId").is(vUserId))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, UserComment.class);
    }

    @Override
    public void save(UserComment userComment) {
        mongoTemplate.save(userComment);
        //4、更新动态表中的字段
        Query query = Query.query(Criteria.where("vid").is(userComment.getVid()));
        Update update = new Update();
        update.inc("commentCount",1);
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true); //获取更新后的最新数据
        mongoTemplate.findAndModify(query, update, options, Video.class);
    }

    @Override
    public UserComment likeOrUnlike(ObjectId id,String type) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = new Update();
        if (type.equals("zan")){
            update.inc("likeCount",1);
        }else {
            update.inc("likeCount",-1);
        }
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true); //获取更新后的最新数据
        UserComment userComment = mongoTemplate.findAndModify(query, update, options, UserComment.class);
        return userComment;
    }
}
